﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace zielonka.co.uk.extensions.system
{
    //Description: Gets the value of a property in a object through relection
    /*
     user.GetPropertyValue<string>("Name");
     */

    /// <summary>
    /// Extension methods for the Type class
    /// </summary>
    public static partial class TypeExtensions
    {
        public static T GetPropertyValue<T>(this object source, string property)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            var sourceType = source.GetType();
            var sourceProperties = sourceType.GetProperties();

            var propertyValue = (from s in sourceProperties
                                 where s.Name.Equals(property)
                                 select s.GetValue(source, null)).FirstOrDefault();

            return propertyValue != null ? (T)propertyValue : default(T);
        }
    }
}
